<?php

namespace IYUU\sdk\CoolQ\Domain;

use CreditsExchangeModel;
use UserModel;

class Credit
{
    /**
     * 加减用户积分
     * @param string $symbol -减积分，+加积分
     * @param int $credits 数值
     * @param int $user_id 用户QQ
     * @param int $handled_by 经手人QQ
     * @param string $content 变动内容或原因
     * @return string|null
     */
    public static function creditsExchange(string $symbol = '-', int $credits = 0, int $user_id = 0, int $handled_by = 0, string $content = ''): ?string
    {
        if (0 >= $credits) {
            return '变动积分必须大于0';
        }
        /**
         * 减积分：积分兑换
         */
        if ('-' === $symbol) {
            // 1. 查询总积分
            $user = UserModel::where('user_id', $user_id)->findOrEmpty();
            if ($user->isEmpty()) {
                return '不存在用户，QQ:' . $user_id;
            }

            // 2. 计算剩余积分
            $balance = $user->credits - $user->credits_exchange;

            // 3. 判断剩余积分是否满足兑换条件
            if ($balance < $credits) {
                return '积分不足，兑换失败！剩余积分：' . $balance;
            }

            // 4. 查询操作员主键
            $by = UserModel::where('user_id', $handled_by)->findOrEmpty();
            if ($by->isEmpty()) {
                return '不存在经手人，QQ:' . $handled_by;
            }
            // 5. 执行兑换操作
            $uid = $user->id;
            $by_uid = $by->id;
            $db_exchange = [
                'uid' => $uid,
                'credits' => $credits,
                'content' => $content,
                'handled_by' => $by_uid,
            ];
            $credits_exchange = CreditsExchangeModel::create($db_exchange);

            // 6. 更新用户兑换积分
            $user->credits_exchange += $credits;
            $user->save();

            return sprintf('[CQ:face,id=125]QQ：%d' . PHP_EOL . '[CQ:face,id=69]兑换积分：%d' . PHP_EOL . '[CQ:face,id=76]目前剩余积分：%d' . PHP_EOL . '[CQ:face,id=66]当前是第%d个兑换者。', $user_id, $credits, $balance - $credits, $credits_exchange->id);
        } else {
            // 加积分：奖励
            // 1. 增加积分
            return null;
        }
    }

    /**
     * 撤销积分兑换
     * - 在操作错误时撤销，冲抵积分，恢复用户积分
     * @param int $id
     * @return string
     */
    public static function deleteCreditsExchange(int $id): string
    {
        return '撤销成功！';
    }
}
